package com.linsen.core.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象类型转换工具
 * @author zhaoyong
 * @date 2023/3/22
 */
public final class ConvertUtil {
    /**
     * 对象转换指定对象
     * @param sourceObject
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> T convert(Object sourceObject, Class<T> targetClass) {
        if (ObjectUtil.isNull(sourceObject)) {
            return null;
        }

        try {
            T targetObject = targetClass.newInstance();
            BeanUtil.copyProperties(sourceObject, targetObject);
            return targetObject;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 对象转换指定对象 可添加忽略属性
     * @param sourceObject
     * @param targetClass
     * @param ignoreProperties
     * @param <T>
     * @return
     */
    public static <T> T convert(Object sourceObject, Class<T> targetClass, String... ignoreProperties) {
        if (ObjectUtil.isNull(sourceObject)) {
            return null;
        }

        try {
            T targetObject = targetClass.newInstance();
            BeanUtil.copyProperties(sourceObject, targetObject, ignoreProperties);
            return targetObject;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 集合对象转换指定集合对象
     * @param sourceList
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> List<T> convert(List<?> sourceList, Class<T> targetClass) {
        List<T> emptyList = new ArrayList<>(0);
        if (CollectionUtil.isEmpty(sourceList)) {
            return emptyList;
        }

        return BeanUtil.copyToList(sourceList, targetClass);
    }

    /**
     * 对象转换指定集合对象
     * @param source
     * @param targetClass
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(Object source, Class<T> targetClass) {
        List<T> list = new ArrayList<>();
        if (source instanceof ArrayList<?>) {
            for (Object o : (List<?>) source) {
                list.add(targetClass.cast(o));
            }
        }

        return list;
    }
}
